package com.youxue.teachin.set.child.my;

import com.library.rest.ApiServiceManager;
import com.library.rest.rxjava.RxResultHelper;
import com.library.rest.rxjava.RxSchedulersHelper;
import com.library.rest.rxjava.ServerException;
import com.library.rest.vo.ResponseModel;
import com.library.uiframework.mvp.BasePresenter;
import com.youxue.teachin.common.utils.DefaultSubscriber;
import com.youxue.teachin.set.repository.ISetRepository;
import com.youxue.teachin.set.repository.po.UserPO;
import rx.Observable;

import static com.library.rest.ApiServiceManager.getOrCreateApiService;

/**
 * 在此写用途
 *
 * @author: zhiwei
 * @date: 2017-10-06 23:33
 * @version: 9.1.0
 */
public class UserChangePresener extends BasePresenter<IChageUserView> {

    /**
     * 构造方法
     *
     * @param o    绑定的视图对象
     */
    public UserChangePresener(IChageUserView o) {
        super(o);
    }

    public static Observable<Void> uploadUser(UserPO userPO) {
        Class<ISetRepository> claxx = ISetRepository.class;
        return getOrCreateApiService(claxx)
            .updateUserInfo(userPO)
            .compose(RxSchedulersHelper.<ResponseModel<Void>>io_main())
            .compose(RxResultHelper.<Void>handleResult());
    }

    public void updateUser(UserPO userPO) {
        Observable<Void> observable = uploadUser(userPO);
        execute(observable, new ChangeSubscriber());
    }

    /**
     * 修改手机号码
     *
     * @param newPhone 新手机号码
     * @param authcode 验证码
     */
    public void changePhone(String newPhone, String authcode) {
        Class<ISetRepository> claxx = ISetRepository.class;
        Observable<Void> observable = ApiServiceManager.getOrCreateApiService(claxx)
            .changePhone(newPhone, authcode)
            .compose(RxSchedulersHelper.<ResponseModel<Void>>io_main())
            .compose(RxResultHelper.<Void>handleResult());
        execute(observable, new ChangeSubscriber());
    }

    public class ChangeSubscriber extends DefaultSubscriber<Void> {

        @Override
        public void onNext(Void aVoid) {
            super.onNext(aVoid);
            mBindView.updateSucces();
        }

        @Override
        public void onError(Throwable e) {
            super.onError(e);
            if (!(e instanceof ServerException)) {
                mBindView.updateFail();
            }
        }
    };
}
